package reference;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author hujian
 * @date 2023/2/15 14:26
 * @description
 */
public class ReferenceTypeDetector {
    public static String detectReferenceType(String reference) {
        // 定义不同类型参考文献的正则表达式
        String bookRegex = "^(?<author>[^\\.]+)\\.(?<title>[^\\.]*)\\.(?<edition>[^\\.]*)\\.(?<place>[^:]+):(?<publisher>[^,]+),\\s*(?<year>[0-9]+)\\.$";
        String journalRegex = "^(?<author>[^\\.]+)\\.(?<title>[^\\.]*)\\.(?<journal>[^,]+),\\s*(?<year>[0-9]+),\\s*(?<volume>[^\\(]+)\\((?<issue>[^\\)]+)\\):\\s*(?<page>[^\\.]+)\\.$";
        String conferenceRegex = "^(?<author>[^\\.]+)\\.(?<title>[^\\.]*)\\.(?<conference>[^,]+),\\s*(?<place>[^,]+),\\s*(?<year>[0-9]+),\\s*(?<page>[^\\.]+)\\.$";
        String thesisRegex = "^(?<author>[^\\.]+)\\.(?<title>[^\\.]*)\\.(?<type>[^\\.]*)\\s*\\[(?<degree>[^\\]]*)\\].\\s*(?<place>[^:]+):(?<university>[^,]+),\\s*(?<year>[0-9]+)\\.$";
        String electronicRegex = "^(?<author>[^\\.]+)\\.(?<title>[^\\.]*)\\[(?<type>[^\\]]+)\\]\\s*(?<medium>[^\\.]*)\\.(?<date>[^\\.]+)\\.(?<accessDate>[^\\.]+)\\.(?<url>[^\\.]+)\\.$";

        // 匹配参考文献的类型
        Pattern bookPattern = Pattern.compile(bookRegex, Pattern.DOTALL);
        Matcher bookMatcher = bookPattern.matcher(reference);
        if (bookMatcher.matches()) {
            return "book";
        }

        Pattern journalPattern = Pattern.compile(journalRegex, Pattern.DOTALL);
        Matcher journalMatcher = journalPattern.matcher(reference);
        if (journalMatcher.matches()) {
            return "journal";
        }

        Pattern conferencePattern = Pattern.compile(conferenceRegex, Pattern.DOTALL);
        Matcher conferenceMatcher = conferencePattern.matcher(reference);
        if (conferenceMatcher.matches()) {
            return "conference";
        }

        Pattern thesisPattern = Pattern.compile(thesisRegex, Pattern.DOTALL);
        Matcher thesisMatcher = thesisPattern.matcher(reference);
        if (thesisMatcher.matches()) {
            return "thesis";
        }

        Pattern electronicPattern = Pattern.compile(electronicRegex, Pattern.DOTALL);
        Matcher electronicMatcher = electronicPattern.matcher(reference);
        if (electronicMatcher.matches()) {
            return "electronic";
        }

        // 如果不匹配任何类型，则返回"unknown"
        return "unknown";
    }

    public static void main(String[] args) {
        String reference1 = "陈臣, 周琪琪, 于海燕, 娄新曼, 李永 and 田怀香 \"蛋白质-香气化合物结合作用的研究方法及影响因素研究进展.\" 食品科学: 1-13.";
        String reference2 = "Wang Wenyuan. Implementing database systems[M]. Beijing: Tsinghua";
        System.out.println(detectReferenceType(reference1));
    }
}
